﻿    google.load('search', '1', {"language" : "ru-ru"});
    

    var show_debug = false;
    var searchControl;
    var questions1 = new Array("Left picture is...", "Center picture is...", "Right pichute is...");
    var questions2 = "What is that?";
    var true_query;
    var cur_image_count = 0;
    var true_image;

    var one_image_height = 200;
    var one_image_width = 150;
    var images_count = questions1.length;
    var triple_captcha_type = 1;
    var blur_captcha_type = 2;
	var triple_captcha_type2 = 3;


    var captchaType = triple_captcha_type2;

    function buildDbRow(q, a)
    {
	  this.query = q;
      this.answers = a;
    }
	
    var qtable1 = new Array(
    	new buildDbRow("корова", new Array("корова", "коровка", "коровы", "cow", "cows")),
		new buildDbRow("бык", new Array("бык", "бычара", "теленок", "быки", "bull", "bulls")),
		new buildDbRow("лошадь", new Array("лошадь", "лошади", "horse", "horses")),
		new buildDbRow("зебра", new Array("зебра", "лошадь", "лошади", "зебры", "horse", "horses", "zebra", "zebras")),
		new buildDbRow("жираф", new Array("жираф", "жирафы", "giraffe", "giraffes")),
		new buildDbRow("лось", new Array("лось", "сохатый", "лоси", "elk", "elks")),
		new buildDbRow("олень", new Array("олень", "олени", "deer", "deers")),
		new buildDbRow("собака", new Array("собака", "собак", "собачка", "кобель", "собаки", "dog", "dogs")),
		new buildDbRow("бегемот", new Array("бегемот", "гиппопотам", "бегемоты", "behemoth", "behemoths"))
	);
	
	function getCanvas()
	{
	  return document.getElementById("CAPTCHAimage");
	}

	function getRandomInt(min, max)
	{
	  return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	function getRandomDouble(min, max)
	{
	  return Math.random() * (max - min) + min;
	}

	function getRandomQuery()
	{
		return qtable1[getRandomInt(0, qtable1.length - 1)];
	}

	function setQuestion(question)
	{
	  document.getElementById("bc_question").innerHTML = question;
	}
	
	function debugOutput(inner_html)
	{
	  if(show_debug)
	  {
        var debugoutput = document.getElementById("debugoutput");
        if(null != debugoutput)
    	  debugoutput.innerHTML = inner_html;
	  }
	}

	function onShowDebug()
	{
	  debugswitcher = document.getElementById("debugswitcher");
	  if(null != debugswitcher)
	  {
	    if(!show_debug)
	    {
	      show_debug = true;
	      debugswitcher.value = "Without debugging";
	    }
	    else
		{
		  debugOutput(null);
		  show_debug = false;
	      debugswitcher.value = "Debugging";
		}
	  }
	}
	
	function onDrawType1(canvas, img, img_index)
	{
      var ctx = canvas.getContext("2d");
      if(cur_image_count == 0)
      {
        var angle = getRandomDouble(-(3.1415/11.0), 3.1415/13.0); 
        canvas.width = images_count * one_image_width;//img.width;
        canvas.height = one_image_height;//img.height;
        ctx.rotate(angle);
      }
      ctx.drawImage(img, img_index * one_image_width, 0, one_image_width, one_image_height);
	}

	function onDrawType2(canvas, img, img_index)
	{
      var ctx = canvas.getContext("2d");
      var angle = getRandomDouble(-(3.1415/11.0), 3.1415/13.0); 
      switch(img_index)
      {
        case 0:
          canvas.width = 2 * one_image_width;//20% перекрытие;
          canvas.height = one_image_height;
          ctx.globalAlpha = 1.0;//getRandomDouble(0.8, 1);
          ctx.rotate(angle);
          ctx.drawImage(img, 0.5 * one_image_width, 0, one_image_width, one_image_height);
          break;
        case 1:
          ctx.globalAlpha = getRandomDouble(0.25, 0.45);
          ctx.rotate(angle);
		  ctx.drawImage(img, 0, 0, one_image_width, one_image_height);
          break;
        case 2:
          ctx.globalAlpha = getRandomDouble(0.25, 0.55);
          ctx.rotate(angle);
          ctx.drawImage(img, 1 * one_image_width, 0, one_image_width, one_image_height);
          break;
      }
	}

	function onDrawType3(canvas, img, img_index)
	{
      var ctx = canvas.getContext("2d");
      canvas.width = one_image_width;//20% перекрытие;
      canvas.height = one_image_height;
      ctx.globalAlpha = 0.333;
      for(var i = 0; i < 3; i++)
      {
//        ctx.rotate(angle);
        ctx.drawImage(img, getRandomDouble(-10.25, 20.45), getRandomDouble(-20.25, 10.45), one_image_width, one_image_height);
      }
      getCanvas().style.display = "";
	}
	
	function onDraw(img, img_index)
	{
	  if(!img.complete)
	  {
	    window.setTimeout(function() { onDraw(img, img_index) }, 500);
	  }
	  else
	  {
        var canvas = document.getElementById("CAPTCHAimage");
	    if(!canvas || !canvas.getContext)
	    {
	      alert("No canvas supported!");
	      throw "no canvas supported";
	    }
	    else switch(captchaType)
	    {
	      case triple_captcha_type:
		    onDrawType1(canvas, img, img_index)
			break;
		  case blur_captcha_type:
		    onDrawType2(canvas, img, img_index);
		    break;
	      case triple_captcha_type2:
		    onDrawType3(canvas, img, img_index);
		    break;
	    }
	    if(img_index == (images_count - 1))
   	      getCanvas().style.display = "";
	  }
	}

	function onSc(sc, searcher) 
	{
      if ( searcher.results && searcher.results.length > 0) 
	  {
	    var res_len = searcher.results.length - 1;
        var result = searcher.results[getRandomInt(0, res_len)];
        var img = new Image();
        img.src = result.url;
		onDraw(img, cur_image_count);
        if(cur_image_count < (images_count - 1))
		  onUpdate(false);
		else
		  debugOutput("query: " + true_query.query + 
	    			  "<br>anss: " + true_query.answers);
      }
      else
      	alert("no results");
    }
      
	function onEnter(key_code)
    {
	  if(key_code == 13 && onSubmit())
		onLoad();
    }

	function onUpdate(reset)
	{
	  if(reset)
	  {
	    cur_image_count = 0;
	    true_query = null;
	    getCanvas().style.display = "none";
	  }
	  else
	    cur_image_count ++;
	    
	  var q = getRandomQuery();
      switch(captchaType)
      {
        case triple_captcha_type:
   	      if(reset)
   	        true_image = getRandomInt(0, images_count - 1);
    	  if(true_image == cur_image_count)
    	  {
			setQuestion(questions1[cur_image_count]);
	        true_query = q;
		  }
          searchControl.execute(q.query);
		  break;
	    case blur_captcha_type:
    	  if(reset)
    	  {
    	    setQuestion(questions2);
	        true_query = q;
    	  }
          searchControl.execute(q.query);
	      break;
        case triple_captcha_type2:
    	  if(reset)
    	  {
    	    setQuestion(questions2);
	        true_query = q;
            searchControl.execute(q.query);
    	  }
	      break;
        
	  }
//	  searchControl.clearAllResults();
	}
	
	function onChangeCaptchaType(type)
	{
	  captchaType = type;
	  onUpdate(true);
	}
	
    function onLoad() 
    {
      document.getElementById("engine_vers").innerHTML = "0.5.2";
	  searchControl = new google.search.SearchControl();
      searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
      searchControl.setSearchCompleteCallback(this, onSc);
      searchControl.addSearcher(new google.search.ImageSearch());
      searchControl.draw(null); //без этого чего-то не фурыкает	  
      cur_image_count = 0;
	  onUpdate(true);
    }

	function onSubmit()
	{
	  var answers = true_query.answers;
  	  var answerfield = document.getElementById("answerfield");
	  for(key in answers) 
	  {
	    var answer = answers[key];
        if(answer.toLowerCase().indexOf(answerfield.value.toLowerCase()) != -1 && answerfield.value.length)
        {
       	  alert("Right!");
      	  answerfield.value = "";
      	  return  true;
        }
      }
  	  alert("No way");
  	  return false;
	}

    google.setOnLoadCallback(onLoad);